package org.ziegler.netty.cp8;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class ThirdServer {

    public static void main(String[] args) throws InterruptedException {
        ThirdServer s = new ThirdServer();
        s.start(8888);
    }

    void start(int port) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(group)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(port))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                System.out.println("thirdServer : channel active");
                            }
                        });
                    }
                });

        ChannelFuture channelFuture = bootstrap.bind().sync();
        channelFuture.addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("ThirdServer bound : " + port);
            } else {
                System.out.println("ThirdServer Bind attempt failed");
            }
        });

    }
}
